﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Media.Imaging;

namespace SongSharp.Presentation.Adapter
{
    public class MultiStateAdapter
    {
        public Image ImageContainer { get; private set; }
        public Dictionary<string, BitmapImage> SpecialImages { get; private set; }
        public BitmapImage[] Images { get; private set; }

        public bool Enabled
        {
            get { return m_enabled; }
            set 
            { 
                m_enabled = value;
                if (m_enabled)
                {
                    ImageContainer.Source = Images[m_stateIndex];
                }
                else
                {
                    SetSpecialImage("disabled", true);
                }
            }
        }

        private int m_stateIndex;
        private bool m_enabled = true;

        public MultiStateAdapter(Image imageContainer, string pressedImage, string disabledImage, string[] stateImages)
        {
            ImageContainer = imageContainer;
            Images = new BitmapImage[stateImages.Length];
            int index = 0;
            foreach (string s in stateImages)
                Images[index++] = new BitmapImage(new Uri(@"pack://application:,,,/SongSharp.Presentation;component/Images/" + s));

            if (pressedImage != null)
                AddSpecialImage("pressed", pressedImage);
            if (disabledImage != null)
                AddSpecialImage("disabled", disabledImage);
        }

        public void NextState()
        {
            if (Enabled)
            {
                if (++m_stateIndex == Images.Length)
                    m_stateIndex = 0;
                ImageContainer.Source = Images[m_stateIndex];
            }
        }

        public void AddSpecialImage(string key, string imageUri)
        {
            if (SpecialImages == null)
                SpecialImages = new Dictionary<string, BitmapImage>();
            SpecialImages.Add(key, new BitmapImage(new Uri(@"pack://application:,,,/SongSharp.Presentation;component/Images/" + imageUri)));
        }

        public void SetSpecialImage(string key, bool suppressEnabledState)
        {
            if (SpecialImages != null && ((!Enabled && suppressEnabledState) || Enabled))
                ImageContainer.Source = SpecialImages[key];
        }

        public void Press()
        {
            SetSpecialImage("pressed", false);
        }
    }
}
